/*
 * Copyright (C) 2011  John Lawrence thegordo.john at gmail.com
 * Licensed under GPLv3 or later. see http://www.gnu.org/copyleft/gpl.html
 */

package org.jklawrencefam.server.smtp;

import org.jklawrencefam.server.smtp.command.*;
import org.jklawrencefam.server.smtp.state.SmtpState;

/**
 * See RFC 5321
 * <p/>
 * User: John Lawrence
 * Date: 5/20/11
 * Time: 12:17 AM
 */
public class SmtpProtocol {
    private SmtpState state;

    public SmtpProtocol() {
        state = new SmtpState();
    }

    public void processCommand(String communication) {
        String[] separated = communication.split(" ");
        String commandString = separated[0];
        SmtpCommand command = SmtpCommandFactory.getCommand(commandString, communication);
        command.setProtocol(this);
        state.setCurrentCommand(command);

    }

    public ActionState getActionState() {
        if (state.getCurrentCommand() instanceof Quit) {
            return ActionState.QUIT;
        } else if (state.getCurrentCommand() instanceof Data) {
            return ActionState.PROLONGED_READ;
        }
        return ActionState.NONE;
    }

    public String getInitialMessage() {
        return SmtpCode.READY.getCode() + " " + getHostname() + " Simple Mail Transfer Service Ready";
    }

    public String getHostname() {
        return "jklawrencefam.info";
    }

    public String getNextMessage() {
        return state.getCurrentCommand().getReplyMessage();
    }

    public void setMessageBody(String messageBody) {
        state.setMessageData(messageBody);
        state.setCurrentCommand(new MailReceived());
    }

    public SmtpState getState() {
        return state;
    }

    public enum ActionState {
        QUIT,
        PROLONGED_READ,
        NONE
    }

}
